package com.book.controller;

import com.book.common.BaseController;
import com.book.common.CommonResult;
import com.book.common.NoRepeatSubmit;
import com.book.dto.BookDto;
import com.book.dto.ImgDto;
import com.book.dto.UserDto;
import com.book.pojo.Category;
import com.book.redis.RedisRandomProvider;
import com.book.remote.BookApiRemote;
import com.book.remote.BrowseHistoryRemote;
import com.book.remote.CategoryRemoter;
import com.book.remote.ImageApi;
import com.book.util.Constants;
import com.book.vo.BookIndexVo;
import com.book.vo.BookNewVo;
import com.book.vo.ResponseVo;
import com.book.vo.UBookVo;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @Author 李锦程
 * @Date 2021/4/7 9:16 下午
 * @Package com.book.controller
 * @Version 1.0
 */
@Slf4j
@Controller
@RequestMapping("/ubook")
public class BookController extends BaseController {
    @Autowired
    private BookApiRemote uBookApi;
    @Autowired
    private ImageApi imageApi;
    @Autowired
    private RedisRandomProvider redisRandomProvider;
    @Autowired
    private CategoryRemoter categoryRemoter;
    @Autowired
    private BrowseHistoryRemote browseHistoryRemote;

    @RequestMapping("/post/index")
    public String postIndex(Model model) {
        List<Category> categoryList = categoryRemoter.getCategoryList(0);
        model.addAttribute("category", categoryList);
        return "book/addBook.jsp";
    }

    @RequestMapping("/post/success")
    public String postSuccess(Model model) {
        return "book/postSuccess.jsp";
    }

    @NoRepeatSubmit
    @RequestMapping("/image/up")
    @ResponseBody
    public CommonResult uploadImg(@RequestParam("file") MultipartFile[] files, HttpSession session, HttpServletResponse response, HttpServletRequest request) {
        try {
            String ubCode = redisRandomProvider.getBookCode();
            if (files != null) {
                log.info("file:{}", files);
                UserDto userDto = (UserDto) session.getAttribute("user");
                for (MultipartFile f : files
                ) {
                    ImgDto imgDto = ImgDto.getInstance();
                    imgDto.setUbCode(ubCode);
                    imageApi.saveImg(imgDto, userDto, f);
                }
            }
            return CommonResult.success(ubCode);
        }catch (Exception e){
            return CommonResult.fail("上传图片失败");
        }
    }

    @NoRepeatSubmit
    @RequestMapping("/post/do")
    @ResponseBody
    public CommonResult postDo(BookDto uBookDto, HttpSession session) {
        UserDto userDto = (UserDto) session.getAttribute("user");
        uBookDto.setUId(userDto.getId());
        log.info("#ubookDto:{}", uBookDto);
        Integer integer = uBookApi.saveUBook(uBookDto);
        if (integer == 1) {
            return CommonResult.successNoMsg();
        }
        return CommonResult.fail("上传失败");
    }

    @RequestMapping("/modify/{id}")
    public String Modify(@PathVariable Integer id, Model model) {
        BookDto uBookDto = uBookApi.getBookById(id);
        log.info("#UBookController.Modify#ookDto:{}", uBookDto);
        model.addAttribute("bto", uBookDto);
        return "book/modify.jsp";
    }

    @RequestMapping("/doModify")
    @ResponseBody
    public String DoModify(BookDto uBookDto) {
        if (uBookDto == null) {
            return Constants.ERROR;
        }
        Integer i = uBookApi.upDataUBook(uBookDto);
        return i == 1 ? Constants.SUCCESS : Constants.ERROR;
    }

    @RequestMapping("/detail/{id}")
    public String Detail(@PathVariable Integer id, Model model) {
        List<BookNewVo> bookThree = uBookApi.getBookThree();
        UBookVo bookById = uBookApi.getUBookDetail(id);
        model.addAttribute("uBookVo", bookById);
        model.addAttribute("img", bookById.getImgUrl().get(0));
        model.addAttribute("newBooks", bookThree);
        model.addAttribute("cateList", categoryRemoter.getCategoryList(0));
        if (getCurrentUser() != null) {
            browseHistoryRemote.editBrowseHistory(getUserCode(), bookById.getUBookDto().getBookCode());
        }
        return "/book/detail.jsp";
    }

    @RequestMapping("/myBooks")
    public String myBook(Model model) {
        Integer currentId = getCurrentId();
        List<BookIndexVo> bookDtos = uBookApi.getBookListByUId(currentId);
        model.addAttribute("voList", bookDtos);
        return "/book/index.jsp";
    }

    @RequestMapping("/mybookList")
    public String myBookLsit(Model model) {
        Integer currentId = getCurrentId();
        List<BookIndexVo> bookDtos = uBookApi.getBookListByUId(currentId);
        bookDtos.forEach(m -> {
            m.setBookTitle(m.getBookTitle().substring(0, 12));
        });
        model.addAttribute("voList", bookDtos);
        return "/user/bookList.jsp";
    }

    @RequestMapping("/searchName")
    @ResponseBody
    public ResponseVo searchName(String bookAuthor) {
        try {
            List<BookIndexVo> voList = uBookApi.queryAuthorOrTitle(1, bookAuthor);
            return ResponseVo.successResult(voList);
        } catch (Exception e) {
            return ResponseVo.errRest("搜索失败");
        }
    }

    @RequestMapping("/searchTitle")
    @ResponseBody
    public ResponseVo searchTitle(String bookTitle) {
        try {
            List<BookIndexVo> voList = uBookApi.queryAuthorOrTitle(2, bookTitle);
            return ResponseVo.successResult(voList);
        } catch (Exception e) {
            return ResponseVo.errRest("搜索失败");
        }
    }

    @RequestMapping("/searchCate")
    @ResponseBody
    public ResponseVo searchTitle(Integer cateId, String queryText) {
        try {
            List<BookIndexVo> query = uBookApi.query(cateId, queryText);
            log.info("searchCate#query:{}", query);
            return ResponseVo.successResult(query);
        } catch (Exception e) {
            log.error("searchCate#异常", e);
            return ResponseVo.errRest("搜索失败");
        }
    }

    @RequestMapping("/queryFilter")
    @ResponseBody
    public ResponseVo queryFilter(Integer cateId, String price) {
        List<BookIndexVo> bookIndexVoList = Lists.newArrayList();
        log.info("queryFilter#cataId:{},re:{}", cateId, cateId == null);
        if (cateId == null) {
            log.info("全部");
            bookIndexVoList = uBookApi.searchFilter(null, price, true);
            return ResponseVo.successResult(bookIndexVoList);
        }
        log.info("分类");
        Category parentCategoryList = categoryRemoter.getParentCategoryList(cateId);
        if (parentCategoryList.getPid() == 0) {
            bookIndexVoList = uBookApi.searchFilter(cateId, price, false);
        } else {
            bookIndexVoList = uBookApi.searchFilter(cateId, price, true);
        }
        return ResponseVo.successResult(bookIndexVoList);
    }

    @RequestMapping("/delte/${id}")
    @ResponseBody
    public ResponseVo delete(@PathVariable Integer id) {
        try {
            Boolean aBoolean = uBookApi.deleteBookById(id);
            return ResponseVo.successResultNotData();
        } catch (Exception e) {
            return ResponseVo.errRest("删除失败");
        }
    }

}
